
// 获取应用实例
import {$request} from '../../utils/request'
import Toast from '../../miniprogram_npm/vant-weapp/toast/toast'
const app = getApp()
Page({
  data: {
    num: 0,
    interval: "",
    isPlay: true,
    // longitude: "123.28",
    // latitude: "40.29",
    longitude:0,
    latitude:0,
    scale: 15,
    enable_zoom:true,
    enable_scroll:true,
    enable_traffic: true,
    show_compass: false,
    route: [],
    routeline:[],
    scenicSpots:[],
    // 当前定位
    get_latitude:0,
    get_longitude:0,
    markers: [],
    alongScenicArea:[],
    isFlag:false,
    isloading:false
  },
  onLoad(options) {
    var _this = this
    var pointfor = []
   

    // this.getalongScenic(options.id);
  

  //获取定位
    wx.getLocation({
      type: 'gcj02', // 比较精确
      success: (res) => {
       console.log(res);
       _this.setData({
         get_latitude:res.latitude,
         get_longitude:res.longitude
       },()=>{
        _this.getalongScenic(options.id);
        _this.setMarkers()
      })
      }
    })
    //通过wx.request发起HTTPS接口请求
  },
   getalongScenic(id){
   console.log('id',id)
   this.setData({ isloading: true })
   wx.showLoading({
    title: '路线加载中',//数据加载得比较慢的时候出现提示
  })
   $request({url:`/route/miniprogram?id=${id}`})
   .then((res)=>{
    console.log('res',res)
 if(res && res.data && res.data.length > 0 && res.data[0].alongScenicAreaVO){
  this.setData({
    alongScenicArea:res.data[0].alongScenicAreaVO,
    scenicSpots: res.data[0].alongScenicAreaVO[0].scenicSpots,
    isloading: false,
    latitude:res.data[0].alongScenicAreaVO[0].scenicAreaLatitude,
    longitude:res.data[0].alongScenicAreaVO[0].scenicAreaLongitude
    
  })
  console.log('alongScenicArea',res.data[0].alongScenicAreaVO)
  console.log('scenicAreaLatitude,scenicAreaLongitude',res.data[0].alongScenicAreaVO[0].scenicAreaLatitude,res.data[0].alongScenicAreaVO[0].scenicAreaLongitude)
  this.fetchRoute();
 } else{
  this.setData({ isloading: false,isFlag: true});
  Toast('线路开发中，敬请期待！');
 } 
   })
   .catch(catcherr => {
    console.error(catcherr);
    this.setData({isFlag:true})
      Toast('线路开发中。。。');
  })
 },
 // 绘制路线
 fetchRoute() {
  const { get_latitude, get_longitude, longitude, latitude } = this.data;
  const _this = this;

  wx.request({
    //用老师的key 21571ff7adb0223185347d34893558f3
    url: `https://restapi.amap.com/v3/direction/driving?key=21571ff7adb0223185347d34893558f3&origin=${get_longitude},${get_latitude}&destination=${longitude},${latitude}&extensions=base&strategy=0`,
    success(res) {
      console.log(res);
      const route = res.data.route;
      const paths = route.paths;
      const steps = paths[0].steps; // 选择第一个路径导航
      const pl = [];

      // 将解压后的坐标放入点串数组pl中
      for (let i = 0; i < steps.length; i++) {
        const polylines = steps[i].polyline.toString().split(";");
        for (let j = 0; j < polylines.length; j++) {
          pl.push({
            longitude: parseFloat(polylines[j].toString().split(",")[0]),
            latitude: parseFloat(polylines[j].toString().split(",")[1])
          });
        }
      }

      _this.setData({
        longitude: longitude,
        latitude: latitude,
        route: pl,
        polyline: [{
          points: pl,
          color: '#58c16c',
          width: 6,
          borderColor: '#2f693c',
          borderWidth: 1
        }],
      }, () => {
        _this.setMarkers();
      });
    },
    fail(err) {
      console.error('获取路线失败', err);
      Toast('无法获取路线，请稍后再试');
    }
  });
},

 setMarkers() {
  const { get_latitude, get_longitude, longitude, latitude } = this.data;
console.log('longitude, latitude',longitude, latitude)
  // 如果起点和终点都有值，则设置标记
  if (get_latitude && get_longitude && longitude && latitude) {
    const marker = [
      {
        iconPath: "https://wechats.oss-cn-beijing.aliyuncs.com/begin.png",
        id: 1,
        longitude: get_longitude,
        latitude: get_latitude,
        height: 40,
        width: 40,
        label: {
                anchorY:-70,
                // content: "起点",
                content:'大连民族大学',
                padding: 5,
                fontSize: 12,
                textAlign: 'center',
                display: 'ALWAYS',
                borderRadius: 5,
                borderWidth: 1,
                bgColor: '#ffffff',
                borderColor: "#c3c3c3"
              },
      },
      {
        iconPath: "https://wechats.oss-cn-beijing.aliyuncs.com/end.png",
        id: 2,
        longitude: longitude,
        latitude: latitude,
        height: 40,
        width: 40,
        label: {
                anchorY:-70,
                // content: "终点",
                content:this.data.alongScenicArea[this.data.alongScenicArea.length-1].scenicAreaName,
                padding: 5,
                fontSize: 12,
                textAlign: 'center',
                display: 'ALWAYS',
                borderRadius: 5,
                borderWidth: 1,
                bgColor: '#ffffff',
                borderColor: "#c3c3c3"
              },
      }
    ];
       // 遍历景区数据并添加标记 有问题现在先标记起点和终点吧
    // this.data.alongScenicArea.forEach((scenic, index) => {
    //   marker.push({
    //     iconPath: "https://wechats.oss-cn-beijing.aliyuncs.com/location.png",
    //     id: index  , // 确保id唯一
    //     longitude: scenic.scenicAreaLongitude,
    //     latitude: scenic.scenicAreaLatitude,
    //     height: 20,
    //     width: 20,
    //     label: {
    //       anchorY: -50,
    //       content: scenic.scenicAreaName,
    //       padding: 5,
    //       fontSize: 12,
    //       textAlign: 'center',
    //       display: 'ALWAYS',
    //       borderRadius: 5,
    //       borderWidth: 1,
    //       bgColor: '#ffffff',
    //       borderColor: "#c3c3c3"
    //     },
    //   });
    // });

    this.setData({
      markers: marker
    });
  }
},
  gotoPage:function () {
    wx.navigateTo({
      url: '../begin/begin', //要跳转到的页面路径
      // url:'../test/test'
    })
  }  
})
